/*!
 @header CircleListViewController.m
 @author 王 文彬
 @version 1.0.0 2013/01/29 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */


//  -业务逻辑细节说明-
//
//  @abstract       本类用于建立、修改、删除圈子。

//  @discussion     通过setCircle方法，传递一个要被修改的圈子信息对象。判断此对象是否为空，如果为空，那么就表明此时用户正在操作新增圈子，否则是管理圈子，可修改可删除。

//  @notes          当前圈子下圈友除自己外，还存在其它人，那就此时不允许用户删除，将删除按钮隐藏。


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

#import "CircleFormViewController.h"
#import "Helper.h"
#import "Config.h"
#import "JMFBase.h"

@interface CircleFormViewController ()

@end

@implementation CircleFormViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //视图背景
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //左侧导航按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //右侧导航按钮：保存
    UIButton* saveButton = [Helper buttonWithStyle:ButtonStyleNavigationDone];
    [saveButton addTarget:self action:@selector(saveButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    

    //输入框的边框背景样式
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 45)];
    imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_010@2x" ofType:@"png"]];
    
    //在输入框背景视图中放文字的label
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(10, 8, 60, 30)];
    label.text = _L(@"title_circle_03");   //圈子名称
    label.font = _SYS_FONT_004;
    
    [imageView addSubview:label];
    
    [self.view addSubview:imageView];
    
    //在输入框背景视图中放修改文字的field
    _circleNameField = [[UITextField alloc] initWithFrame:CGRectMake(90, 18, 200, 30)];
    _circleNameField.textColor = _SYS_COLOR_002;
    _circleNameField.font = _SYS_FONT_002;
    [_circleNameField becomeFirstResponder];
    _circleNameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _circleNameField.borderStyle = UITextBorderStyleRoundedRect;
    _circleNameField.placeholder = _L(@"holder_08");    //1到10个字符，支持中英文数字
    
    [self.view addSubview:_circleNameField];
    
    //删除圈子按钮
    _removeButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 100, 300, 45)];
    _removeButton.titleLabel.font = _SYS_FONT_009;
    _removeButton.hidden = true;
    [_removeButton setTitle:_L(@"btn_delete_03") forState:UIControlStateNormal];    //删除圈子
    [_removeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_removeButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_007_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_removeButton addTarget:self action:@selector(removeButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_removeButton];
    
    
    //刷新一下组件状态，现在有可能已经有_circel被设定了（第一次实例创建情况下）
    //title也会由resetView来决定
    [self resetView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*!
 @abstract 获取到圈子信息
 @param circle 圈子信息对象
 */
- (void)setCircle:(NSDictionary *)circle
{
    _circle = circle;
    
    //有Circle被设置，就刷新一下组件状态
    [self resetView];
}

#pragma mark - 私有方法

/*!
 @abstract 用于根据当前类中各状态，刷新组件状态
 */
- (void)resetView
{
    if (_circle != nil) {
        
        self.title = _L(@"vc_title_029");    //圈子设置
        
        //填充圈子的名字
        _circleNameField.text = [_circle valueForKey:@"name"];

        //如果圈子下面的人的数量，<=1，就显示删除按钮。（如果没有设定，或设定_circle的值为nil，则也会取出0，即为假）
        if ([[_circle valueForKey:@"memberCount"] intValue] <= 1) {
            
            _removeButton.hidden = false;
        }
        //否则就隐藏删除按钮
        else {
            
            _removeButton.hidden = true;
        }
    }
    else {
        
        self.title = _L(@"vc_title_030");    //添加圈子
    }
}


#pragma mark - 返回按钮流程

/*!
 @abstract 返回按钮点击事件
 */
- (void)backButtonEvent
{
    if ((_circle && ![_circle[@"name"] isEqualToString:_circleNameField.text]) || (!_circle && _circleNameField.text.length > 0)) {
        
        NSString* alertString = _circle ? _L(@"alert_85") : _L(@"alert_84");
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:alertString delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        alertView.tag = 1;
        [alertView show];
    }
    else {
        if (_circle == nil) {
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
        else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
}


#pragma mark - 按钮事件
/*!
 @abstract 保存按钮点击事件
 */
- (void)saveButtonEvent
{
    //点击了保存按钮，要取消第一响应，让键盘弹出，避免下次打开视图时，键盘遮挡删除按钮
    [_circleNameField resignFirstResponder];
    
    //如果文字一样，说明没有修改，直接返回，不需请求
    if ([_circleNameField.text compare:[_circle objectForKey:@"name"]] == NSOrderedSame) {
        [self backButtonEvent];
        return;
    }

    //请求实例
    JSONRequest* request;
    if (_circle == nil) {
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_ADD];
    }
    else {
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_CHANGE_NAME];
        [request setValue:_circle[@"id"] forParameter:@"circleId"];
    }

    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_05");
    
    [request setValue:_circleNameField.text forParameter:@"circleName"];
    [request asynchronous];
}

/*!
 @abstract 删除圈子按钮点击事件
 */
- (void)removeButtonEvent
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:_L(@"alert_23") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
    alertView.tag = 2;
    [alertView show];
    
}


#pragma mark - JSONRequestDelegate
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {
        if (_circle == nil) {
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
        else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}


- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1 && alertView.tag == 2) {
        
        //请求实例
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_REMOVE];
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_01");
        request.delegate = self;

        [request setValue:[_circle objectForKey:@"id"] forParameter:@"circleId"];
        [request asynchronous];
    }
    else if (buttonIndex == 1 && alertView.tag == 1) {
        if (_circle == nil) {
            [self.navigationController dismissModalViewControllerAnimated:true];
        }
        else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
}


@end
